package com.caotinging.taskdemo.controller;

import com.caotinging.taskdemo.config.DefaultSchedulingConfigurer;
import com.caotinging.taskdemo.dao.DynamicTaskMapper;
import com.caotinging.taskdemo.datetocron.DateToCron;
import com.caotinging.taskdemo.model.DynamicTask;
import com.caotinging.taskdemo.schedule.SchedulingRunnable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class CronController {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    DynamicTaskMapper dynamicTaskMapper;
    @Resource
    private DefaultSchedulingConfigurer defaultSchedulingConfigurer;

    @GetMapping("zhy")
    public void zhy() throws InterruptedException, ParseException {
        /*while (!defaultSchedulingConfigurer.inited()){
            Thread.sleep(100);
        }*/
        /*DynamicTask dynamicTask = dynamicTaskMapper.selectById(2);
        SchedulingRunnable task = new SchedulingRunnable("demoTask", "taskWithParams", "task",dynamicTask.getCron(),dynamicTask.getId());
        SchedulingRunnable task1 = new SchedulingRunnable("demoTask", "taskWithParams", "task1",dynamicTask.getCron(),dynamicTask.getId());

        defaultSchedulingConfigurer.addTriggerTask("task",
                new TriggerTask(task,new CronTrigger("0/5 * * * * ? ")));*/

        String dateStr = "2021-7-24 16:28:00";
        Date parse = simpleDateFormat.parse(dateStr);

        String cronStr = DateToCron.getCron(parse);
        SchedulingRunnable task1 = new SchedulingRunnable("demoTask", "taskWithParams", "task1",cronStr,333);

        defaultSchedulingConfigurer.addTriggerTask("task1",
                new TriggerTask(task1,new CronTrigger("00 37 16 24 07 ? 2021")));
    }


    @GetMapping("uzhy")
    public void uzhy(){
        defaultSchedulingConfigurer.cancelTriggerTask("task");
    }
}
